package bookless.pakage;

import java.util.ArrayList;
import databases.BookDB;
import databases.UserBookDB;
import databases.UserDB;
import activities.AddBookActivity;
import activities.AdminActivity;
import activities.BookSearchActivity;
import activities.MyPageActivity;
import activities.NewUserActivity;
import activities.RemoveBookActivity;
import android.content.Context;

public class StorageHandler {
	private static long bookId;
	private static long userId;
	public static boolean didStoringBookWork;

	public StorageHandler() {

	}

	/**
	 * Stores a book in the book database and make that connection between the
	 * user that stored the book and the book.
	 * 
	 * @param book
	 *            the book that will be stored
	 */
	public static void storeBook(Book book) {

		String bookTitle = book.getTitle();
		String author = book.getAuthor();
		String price = book.getPrice();
		String comment = book.getComments();

		didStoringBookWork = true;

		BookDB bookEntry = new BookDB(AddBookActivity.getContext());
		UserDB userEntry = new UserDB(AddBookActivity.getContext());

		try {
			bookEntry.open();
			bookId = bookEntry.createEntry(bookTitle, author, price, comment);
			bookEntry.close();

		} catch (Exception e) {
			didStoringBookWork = false;
		} finally {
		}

		if (didStoringBookWork) {
			try {
				userEntry.open();
				UserBookDB userBookEntry = new UserBookDB(
						AddBookActivity.getContext());
				userId = userEntry.getUserId(UserHandler.session);
				userBookEntry.open();
				userBookEntry.createEntry(bookId, userId);
				userBookEntry.close();

			} catch (Exception e) {

			}finally {}
		}
	}

	/**
	 * Stores a user in the user database.
	 * 
	 * @param user
	 *            the user that will be stored
	 */
	public static void storeUser(User user) {

		try {
			String userName = user.getUserName();
			String password = user.getPassword();
			UserDB entry = new UserDB(NewUserActivity.getContext());
			entry.open();
			entry.createEntry(userName, password);
			entry.close();
		} catch (Exception e) {			
		} finally {}

	}


	/**
	 * Not implemented
	 **/
	public static Book getBook(Book book) {
		return book;
	}

	/**
	 * Gets all books from the book database that is written by the author
	 * 
	 * @param author
	 *            the author that written the books in the list
	 * @return ArrayList with books
	 */
	public static ArrayList<Book> getBooksByAuthor(String author) {
		
		ArrayList<Book> list = new ArrayList<Book>();

		BookDB bookEntry = new BookDB(BookSearchActivity.getContext());
		bookEntry.open();
		list = bookEntry.getBooksByAuthor(author);
		bookEntry.close();
		return list;
	}


	/**
	 * Returns all the books from the book database
	 * 
	 * @return ArrayList with books
	 */
	public static ArrayList<Book> getAllBooks() {

		ArrayList<Book> list = new ArrayList<Book>();

		BookDB bookEntry = new BookDB(BookSearchActivity.getContext());
		bookEntry.open();
		list = bookEntry.getAllBooks();
		bookEntry.close();
		return list;
	}

	/**
	 * Return a list with all books from the database with the title
	 * 
	 * @param title
	 *            the title on the books on the list
	 * @return ArrayList with books
	 */
	public static ArrayList<Book> getBooksByTitle(String title) {

		ArrayList<Book> list = new ArrayList<Book>();

		BookDB bookEntry = new BookDB(BookSearchActivity.getContext());
		bookEntry.open();
		list = bookEntry.getBooksByTitle(title);
		bookEntry.close();
		return list;
	}


	/**
	 * Removes the book with a specific title added by a user. Removes the
	 * connection between the book and user in the UserBook database.
	 * 
	 * @param userName
	 *            the user that added the book
	 * @param title
	 *            the title on the books that will be removed
	 */
	public static void removeBook(String userName, String title) {

		ArrayList<Long> removedIds = new ArrayList<Long>();
		ArrayList<Book> myList = new ArrayList<Book>();
		myList = getMyBooks(userName);

		Book book = null;

		for (Book b : myList) {
			if (b.getTitle().equals(title)) {
				book = b;
				break;
			}
		}
		if (book != null) {
			BookDB bookEntry = new BookDB(RemoveBookActivity.getContext());
			bookEntry.open();
			removedIds = bookEntry.deleteBook(book);
			bookEntry.close();

			UserBookDB userBookEntry = new UserBookDB(
					RemoveBookActivity.getContext());
			userBookEntry.open();
			for (Long i : removedIds) {
				userBookEntry.deleteUserBook(i);
			}
			userBookEntry.close();
		}

	}


	/**
	 * Return a user given the userName
	 * 
	 * @param userName
	 *            the unique name of a user
	 * @param context
	 *            the context from the page the method was evoked
	 * @return User
	 */
	public static User getUser(String userName, Context context) {

		UserDB userDB = new UserDB(context);
		userDB.open();
		User user = userDB.getUserfromDB(userName);
		userDB.close();

		return user;
	}

	/**
	 * Returns a list with all the book a user has added
	 * 
	 * @param session
	 *            the user that is logged in
	 * @return ArrayList with books
	 */
	public static ArrayList<Book> getMyBooks(String session) {

		ArrayList<Book> bookList = new ArrayList<Book>();

		UserDB userdb = new UserDB(MyPageActivity.getContext());
		userdb.open();
		long userId = userdb.getUserId(session);
		userdb.close();

		UserBookDB userbookdb = new UserBookDB(MyPageActivity.getContext());
		userbookdb.open();
		ArrayList<Long> ids = userbookdb.getBookIds(userId);
		userbookdb.close();

		BookDB bookdb = new BookDB(MyPageActivity.getContext());
		bookdb.open();

		for (long i : ids) {
			bookList.add(bookdb.getBookById(i));
		}
		bookdb.close();

		return bookList;
	}

	/**
	 * Remove the user in session, also removes all connections between the
	 * user and it's books, finally all books from the books database that the
	 * user added will be removed
	 * 
	 * @param session the user that is logged in
	 */
	public static void removeUser(String session) {

		UserDB userdb = new UserDB(MyPageActivity.getContext());
		userdb.open();
		long userId = userdb.getUserId(session);
		userdb.removeUser(session);
		userdb.close();
		
		
		UserBookDB userbookdb = new UserBookDB(MyPageActivity.getContext());
		userbookdb.open();
		ArrayList<Long> bookIds = userbookdb.getBookIds(userId);
		if (bookIds.size() != 0) {
			for (long i : bookIds) {
				userbookdb.deleteUserBook(i);
			}
			
			BookDB bookdb = new BookDB(MyPageActivity.getContext());
			bookdb.open();
			for (long i : bookIds) {
				bookdb.deleteBookById(i);
			}
			bookdb.close();
		}
		userbookdb.close();
	}

	/**
	 * Remove all users, books and all connections between user and books in the databases.
	 */
	public static void removeAllUsers() {

		UserDB userdb = new UserDB(AdminActivity.getContext());
		userdb.open();
		userdb.removeAllUsers();

		BookDB bookdb = new BookDB(AdminActivity.getContext());
		bookdb.open();
		bookdb.removeAllBooks();
		bookdb.close();

		UserBookDB userbookdb = new UserBookDB(AdminActivity.getContext());
		userbookdb.open();
		userbookdb.removeAllConnections();
		userbookdb.close();
	}
}
